﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XStudio.XCRF.Data.Business;
using XStudio.XCRF.Data.Business.Permissions;
using XStudio.XCRF.Data.Entities;
using XStudio.XCRF.Data.Entities.BasicInfo;
using Telerik.Web.Mvc;
using XStudio.XCRF.Web.Models.Enums;

namespace XStudio.XCRF.Web.Controllers
{
    /// <summary>
    /// 基本信息控制器
    /// </summary>
    [DefaultPermission(PermissionType.Allow)]
    public partial class BasicInfoController : BaseController
    {
        #region 基本信息
        public ActionResult BasicInfoAdd(Guid crfID)
        {
            CRF crf = DataContext.CRFs.Include(c => c.Patient).Find(crfID);
            BasicInfo basicInfo = new BasicInfo
            {
                CRFID = crfID,
                CRF = crf
            };
            return View(basicInfo);
        }

        [HttpPost]
        public ActionResult BasicInfoAdd(BasicInfo basicInfo)
        {
            try
            {
                BasicInfo basicinfo_db = new BasicInfo();
                basicinfo_db.CRFID = basicInfo.CRFID;
                basicinfo_db.AgreeTime = basicInfo.AgreeTime;
                basicinfo_db.MedicineCode = basicInfo.MedicineCode;
                basicinfo_db.Height = basicInfo.Height;
                basicinfo_db.Weight = basicInfo.Weight;
                basicinfo_db.Course = basicInfo.Course;
                DataContext.BasicInfoes.Add(basicinfo_db);
                DataContext.SaveChanges();
                return Json(new { ID = basicinfo_db.ID });
            }
            catch
            {
                return Json(null);
            }
        }

        public ActionResult BasicInfoDetail(Guid basicInfoID)
        {
            BasicInfo basicInfo = DataContext.BasicInfoes.Include(b => b.CRF).Include(b => b.CRF.Patient).Find(basicInfoID);
            DbEntityEntry<BasicInfo> entry = DataContext.Entry<BasicInfo>(basicInfo);
            entry.Collection<FamilyHistory>(b => b.FamilyHistories).Query().GetMasterRecords().Load();
            entry.Collection<AllergyHistory>(b => b.AllergyHistories).Query().GetMasterRecords().Load();
            entry.Collection<BasicChemo>(b => b.Chemos).Query().GetMasterRecords().Load();
            entry.Collection<BasicRadio>(b => b.Radios).Query().GetMasterRecords().Load();
            entry.Collection<BasicOtherCure>(b => b.OtherCures).Query().GetMasterRecords().Load();
            entry.Collection<BasicOtherMerge>(b => b.OtherMerges).Query().GetMasterRecords().Load();
            return View(basicInfo);
        }

        public ActionResult BasicInfoEdit(Guid basicInfoID)
        {
            BasicInfo basicInfo = DataContext.BasicInfoes
                .Include(b => b.CRF)
                .Include(b => b.CRF.Patient)
                .Find(basicInfoID);
            return View(basicInfo);
        }

        [HttpPost]
        public ActionResult BasicInfoEdit(BasicInfo basicInfo)
        {
            try
            {
                BasicInfo basicinfo_db = DataContext.BasicInfoes
                    .Include(b => b.CRF)
                    .Include(b => b.CRF.Patient).Find(basicInfo.ID);
                Patient patient_db = basicinfo_db.CRF.Patient;
                basicinfo_db.AgreeTime = basicInfo.AgreeTime;
                basicinfo_db.MedicineCode = basicInfo.MedicineCode;
                patient_db.Gender = basicInfo.CRF.Patient.Gender;
                patient_db.Birthday = basicInfo.CRF.Patient.Birthday;
                basicinfo_db.Height = basicInfo.Height;
                basicinfo_db.Weight = basicInfo.Weight;
                basicinfo_db.Distance = basicInfo.Distance;
                patient_db.Phone = basicInfo.CRF.Patient.Phone;
                basicinfo_db.Course = basicInfo.Course;
                basicinfo_db.WestDiagnose = basicInfo.WestDiagnose;
                basicinfo_db.CaseCode = basicInfo.CaseCode;
                basicinfo_db.PathologyCode = basicInfo.PathologyCode;
                basicinfo_db.Distance = basicInfo.Distance;
                basicinfo_db.OperationHospital = basicInfo.OperationHospital;
                basicinfo_db.OperationTime = basicInfo.OperationTime;
                basicinfo_db.TumorLength = basicInfo.TumorLength;
                basicinfo_db.TumorWidth = basicInfo.TumorWidth;
                basicinfo_db.TumorHeight = basicInfo.TumorHeight;
                basicinfo_db.PathologyType = basicInfo.PathologyType;
                basicinfo_db.InfiltrationPlace = basicInfo.InfiltrationPlace;
                basicinfo_db.PulseEmbolus = basicInfo.PulseEmbolus;
                basicinfo_db.Split = basicInfo.Split;
                basicinfo_db.LymphMove = basicInfo.LymphMove;
                basicinfo_db.TopCutEdge = basicInfo.TopCutEdge;
                basicinfo_db.BottomCutEdge = basicInfo.BottomCutEdge;
                basicinfo_db.TumorPlace = basicInfo.TumorPlace;
                basicinfo_db.KPS = basicInfo.KPS;
                basicinfo_db.ECOG = basicInfo.ECOG;
                basicinfo_db.TNM = basicInfo.TNM;
                basicinfo_db.Dukes = basicInfo.Dukes;
                basicinfo_db.Temperature = basicInfo.Temperature;
                basicinfo_db.HeartRate = basicInfo.HeartRate;
                basicinfo_db.Breath = basicInfo.Breath;
                basicinfo_db.MaxBP = basicInfo.MaxBP;
                basicinfo_db.MinBP = basicInfo.MinBP;

                basicinfo_db.DiaTime = basicInfo.DiaTime;
                basicinfo_db.ffzybw = basicInfo.ffzybw;
                basicinfo_db.ffzyqk = basicInfo.ffzyqk;
                basicinfo_db.fs = basicInfo.fs;
                basicinfo_db.fxzysj = basicInfo.fxzysj;
                basicinfo_db.Oper = basicInfo.Oper;
                basicinfo_db.swf = basicInfo.swf;
                basicinfo_db.swyy = basicInfo.swyy;
                basicinfo_db.wjzscsj = basicInfo.wjzscsj;
                basicinfo_db.xs = basicInfo.xs;
                basicinfo_db.zytj = basicInfo.zytj;
                DataContext.SaveChanges();
                return Json(new { ID = basicInfo.ID });
            }
            catch
            {
                return Json(null);
            }
        }
        #endregion 基本信息

        #region 家族史
        
        /// <summary>
        /// 处理显示家族史部分页请求
        /// </summary>
        /// <param name="basicInfoID">基本信息ID</param>
        /// <returns></returns>
        [HttpPost]
        public PartialViewResult FamilyHistoryList(Guid basicInfoID)
        {
            List<FamilyHistory> histories = DataContext.FamilyHistories
                .Find(f => f.BasicInfoID == basicInfoID).ToList();
            return PartialView(histories);
        }

        /// <summary>
        /// 处理显示家族史编辑模式请求
        /// </summary>
        /// <param name="basciInfoID">基本信息ID</param>
        /// <returns></returns>
        [HttpPost]
        public PartialViewResult FamilyHistoryGridView(Guid basciInfoID)
        {
            BasicInfo basicInfo = DataContext.BasicInfoes.Find(basciInfoID);
            return PartialView(basicInfo);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _FamilyHistoryList(Guid basicInfoID)
        {
            IEnumerable<FamilyHistory> dtos = DataContext.FamilyHistories
                .Find(f => f.BasicInfoID == basicInfoID).ToList()
                .Select(f => new FamilyHistory
                {
                    ID = f.ID,
                    Content = f.Content
                });
            return View(new GridModel(dtos));
        }

        [GridAction]
        [HttpPost]
        public ActionResult _FamilyHistoryAdd(FamilyHistory history, Guid basicInfoID)
        {
            history.BasicInfoID = basicInfoID;
            DataContext.FamilyHistories.Add(history);
            DataContext.SaveChanges();
            return _FamilyHistoryList(basicInfoID);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _FamilyHistoryEdit(FamilyHistory history)
        {
            FamilyHistory history_db = DataContext.FamilyHistories.Find(history.ID);
            history_db.Content = history.Content;
            DataContext.SaveChanges();
            return _FamilyHistoryList((Guid)history_db.BasicInfoID);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _FamilyHistoryDelete(FamilyHistory history)
        {
            FamilyHistory history_db = DataContext.FamilyHistories.Find(history.ID);
            history.BasicInfoID = history_db.BasicInfoID;
            DataContext.FamilyHistories.Remove(history_db);
            DataContext.SaveChanges();
            return _FamilyHistoryList((Guid)history.BasicInfoID);
        }

        #endregion 家族史

        #region 过敏史

        /// <summary>
        /// 处理显示过敏史部分页请求
        /// </summary>
        /// <param name="basicInfoID">基本信息ID</param>
        /// <returns></returns>
        [HttpPost]
        public PartialViewResult AllergyHistoryList(Guid basicInfoID)
        {
            List<AllergyHistory> histories = DataContext.AllergyHistories
                .Find(a => a.BasicInfoID == basicInfoID).ToList();
            return PartialView(histories);
        }

        /// <summary>
        /// 处理过敏史编辑页面请求
        /// </summary>
        /// <param name="basicInfoID">基本信息ID</param>
        /// <returns></returns>
        [HttpPost]
        public PartialViewResult AllergyHistoryGridView(Guid basicInfoID)
        {
            BasicInfo basicInfo = DataContext.BasicInfoes.Find(basicInfoID);
            return PartialView(basicInfo);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _AllergyHistoryList(Guid basicInfoID)
        {
            IQueryable<AllergyHistory> histories = DataContext.AllergyHistories
                .Find(a => a.BasicInfoID == basicInfoID).OrderBy(a => a.CreateTime);
            IEnumerable<AllergyHistory> dtos = DataContext.AllergyHistories
                .Find(a => a.BasicInfoID == basicInfoID).OrderBy(a => a.CreateTime)
                .ToList().Select(a => new AllergyHistory
                {
                    ID = a.ID,
                    Content = a.Content
                });
            return View(new GridModel(dtos));
        }

        [GridAction]
        [HttpPost]
        public ActionResult _AllergyHistoryAdd(AllergyHistory history, Guid basicInfoID)
        {
            history.BasicInfoID = basicInfoID;
            DataContext.AllergyHistories.Add(history);
            DataContext.SaveChanges();
            return _AllergyHistoryList(basicInfoID);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _AllergyHistoryEdit(AllergyHistory history)
        {
            AllergyHistory history_db = DataContext.AllergyHistories.Find(history.ID);
            history.BasicInfoID = history_db.BasicInfoID;
            history_db.Content = history.Content;
            DataContext.SaveChanges();
            return _AllergyHistoryList((Guid)history.BasicInfoID);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _AllergyHistoryDelete(AllergyHistory history)
        {
            AllergyHistory history_db = DataContext.AllergyHistories.Find(history.ID);
            history.BasicInfoID = history_db.BasicInfoID;
            DataContext.AllergyHistories.Remove(history_db);
            DataContext.SaveChanges();
            return _AllergyHistoryList((Guid)history.BasicInfoID);
        }

        #endregion 过敏史

        #region 化疗信息

        /// <summary>
        /// 处理基本信息化疗信息表格编辑页面请求
        /// </summary>
        /// <param name="basicInfoID">基本信息ID</param>
        /// <returns></returns>
        [HttpPost]
        public PartialViewResult BasicChemoGridView(Guid basicInfoID)
        {
            BasicInfo basicInfo = DataContext.BasicInfoes.Find(basicInfoID);
            return PartialView(basicInfo);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicChemoList(Guid basicInfoID)
        {
            IEnumerable<BasicChemo> dtos = DataContext.BasicChemoes.Find(c => c.BasicInfoID == basicInfoID).ToList()
                .Select(c => new BasicChemo
                {
                    ID = c.ID,
                    Scheme = c.Scheme,
                    StartTime = c.StartTime,
                    EndTime = c.EndTime,
                    Remark = c.Remark
                });
            return View(new GridModel(dtos));
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicChemoAdd(BasicChemo chemo, Guid basicInfoID)
        {
            DataContext.BasicChemoes.Add(chemo);
            DataContext.SaveChanges();
            return _BasicChemoList(basicInfoID);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicChemoEdit(BasicChemo chemo)
        {
            BasicChemo chemo_db = DataContext.BasicChemoes.Find(chemo.ID);
            chemo_db.Scheme = chemo.Scheme;
            chemo_db.StartTime = chemo.StartTime;
            chemo_db.EndTime = chemo.EndTime;
            chemo_db.Remark = chemo.Remark;
            DataContext.SaveChanges();
            return _BasicChemoList((Guid)chemo_db.BasicInfoID);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicChemoDelete(BasicChemo chemo)
        {
            BasicChemo chemo_db = ((IQueryable<BasicChemo>)DataContext.BasicChemoes).Find(chemo.ID);
            chemo.BasicInfoID = chemo_db.BasicInfoID;
            DataContext.BasicChemoes.Remove(chemo_db);
            DataContext.SaveChanges();
            return _BasicChemoList((Guid)chemo.BasicInfoID);
        }

        #endregion 化疗信息

        #region 放疗信息
        /// <summary>
        /// 处理基本信息放疗信息编辑表格页面请求
        /// </summary>
        /// <param name="basicInfoID">基本信息ID</param>
        /// <returns></returns>
        [HttpPost]
        public PartialViewResult BasicRadioGridView(Guid basicInfoID)
        {
            BasicInfo basicInfo = DataContext.BasicInfoes.Find(basicInfoID);
            return PartialView(basicInfo);
        }

        /// <summary>
        /// 处理基本信息放疗信息表格数据请求
        /// </summary>
        /// <param name="searchModel"></param>
        /// <param name="basicInfoID">基本信息ID</param>
        /// <returns></returns>
        [GridAction]
        [HttpPost]
        public ActionResult _BasicRadioList(Guid basicInfoID)
        {
            IEnumerable<BasicRadio> dtos = DataContext.BasicRadioes.Find(c => c.BasicInfoID == basicInfoID).ToList()
                .Select(c => new BasicRadio
                {
                    ID = c.ID,
                    Place = c.Place,
                    Dose = c.Dose,
                    Times = c.Times,
                    Remark = c.Remark
                });
            return View(new GridModel(dtos));
        }

        /// <summary>
        /// 处理添加基本信息放疗信息POST请求
        /// </summary>
        /// <param name="radio">欲添加的放疗信息</param>
        /// <param name="basicInfoID">基本信息ID</param>
        /// <returns></returns>
        [GridAction]
        [HttpPost]
        public ActionResult _BasicRadioAdd(BasicRadio radio, Guid basicInfoID)
        {
            DataContext.BasicRadioes.Add(radio);
            DataContext.SaveChanges();
            return _BasicRadioList(basicInfoID);
        }
        /// <summary>
        /// 处理编辑基本信息放疗信息POST请求
        /// </summary>
        /// <param name="radio">欲编辑的放疗信息</param>
        /// <param name="basicInfoID">基本信息ID</param>
        /// <returns></returns>
        [GridAction]
        [HttpPost]
        public ActionResult _BasicRadioEdit(BasicRadio radio)
        {
            BasicRadio radio_db = DataContext.BasicRadioes.Find(radio.ID);
            radio_db.Place = radio.Place;
            radio_db.Dose = radio.Dose;
            radio_db.Times = radio.Times;
            radio_db.Remark = radio.Remark; ;
            DataContext.SaveChanges();
            return _BasicRadioList((Guid)radio_db.BasicInfoID);
        }
        /// <summary>
        /// 处理删除基本信息放疗信息的POST请求
        /// </summary>
        /// <param name="radio">欲删除的放疗信息</param>
        /// <returns></returns>
        [GridAction]
        [HttpPost]
        public ActionResult _BasicRadioDelete(BasicRadio radio)
        {
            BasicRadio radio_db = ((IQueryable<BasicRadio>)DataContext.BasicRadioes).Find(radio.ID);
            radio.BasicInfoID = radio_db.BasicInfoID;
            DataContext.BasicRadioes.Remove(radio_db);
            DataContext.SaveChanges();
            return _BasicRadioList((Guid)radio.BasicInfoID);
        }

        #endregion 放疗信息

        #region 其他治疗信息

        [HttpPost]
        public PartialViewResult BasicOtherCureGridView(Guid basicInfoID)
        {
            BasicInfo basicInfo = DataContext.BasicInfoes.Find(basicInfoID);
            return PartialView(basicInfo);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicOtherCureList(Guid basicInfoID)
        {
            IEnumerable<BasicOtherCure> dtos = DataContext.BasicOtherCures.Find(c => c.BasicInfoID == basicInfoID).ToList()
                .Select(c => new BasicOtherCure
                {
                    ID = c.ID,
                    Name = c.Name,
                    StartTime = c.StartTime,
                    EndTime = c.EndTime,
                    Remark = c.Remark
                });
            return View(new GridModel(dtos));
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicOtherCureAdd(BasicOtherCure otherCure, Guid basicInfoID)
        {
            DataContext.BasicOtherCures.Add(otherCure);
            DataContext.SaveChanges();
            return _BasicOtherCureList(basicInfoID);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicOtherCureEdit(BasicOtherCure otherCure)
        {
            BasicOtherCure otherCure_db = DataContext.BasicOtherCures.Find(otherCure.ID);
            otherCure_db.Name = otherCure.Name;
            otherCure_db.StartTime = otherCure.StartTime;
            otherCure_db.EndTime = otherCure.EndTime;
            otherCure_db.Remark = otherCure.Remark;
            DataContext.SaveChanges();
            return _BasicOtherCureList((Guid)otherCure_db.BasicInfoID);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicOtherCureDelete(BasicOtherCure otherCure)
        {
            BasicOtherCure otherCure_db = ((IQueryable<BasicOtherCure>)DataContext.BasicOtherCures).Find(otherCure.ID);
            otherCure.BasicInfoID = otherCure_db.BasicInfoID;
            DataContext.BasicOtherCures.Remove(otherCure_db);
            DataContext.SaveChanges();
            return _BasicOtherCureList((Guid)otherCure.BasicInfoID);
        }

        #endregion 其他治疗信息

        #region 合并其它疾病及用药

        [HttpPost]
        public PartialViewResult BasicOtherMergeGridView(Guid basicInfoID)
        {
            BasicInfo basicInfo = DataContext.BasicInfoes.Find(basicInfoID);
            return PartialView(basicInfo);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicOtherMergeList(Guid basicInfoID)
        {
            IEnumerable<BasicOtherMerge> dtos = DataContext.BasicOtherMerges
                .Find(m => m.BasicInfoID == basicInfoID).OrderBy(m => m.CreateTime).ToList()
                .Select(m => new BasicOtherMerge
                {
                    ID = m.ID,
                    DrugName = m.DrugName,
                    Diagnose = m.Diagnose,
                    Dose = m.Dose,
                    StartTime = m.StartTime,
                    EndTime = m.EndTime,
                    Effect = m.Effect,
                    Remark = m.Remark
                });
            return View(new GridModel(dtos));
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicOtherMergeAdd(BasicOtherMerge otherMerge, Guid basicInfoID)
        {
            otherMerge.BasicInfoID = basicInfoID;
            DataContext.BasicOtherMerges.Add(otherMerge);
            DataContext.SaveChanges();
            return _BasicOtherMergeList(basicInfoID);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicOtherMergeEdit(BasicOtherMerge otherMerge)
        {
            BasicOtherMerge otherMerge_db = ((IQueryable<BasicOtherMerge>)DataContext.BasicOtherMerges).Find(otherMerge.ID);
            otherMerge_db.Diagnose = otherMerge.Diagnose;
            otherMerge_db.DrugName = otherMerge.DrugName;
            otherMerge_db.Dose = otherMerge.Dose;
            otherMerge_db.StartTime = otherMerge.StartTime;
            otherMerge_db.EndTime = otherMerge.EndTime;
            otherMerge_db.Effect = otherMerge.Effect;
            otherMerge_db.Remark = otherMerge.Remark;
            DataContext.SaveChanges();
            return _BasicOtherMergeList((Guid)otherMerge_db.BasicInfoID);
        }

        [GridAction]
        [HttpPost]
        public ActionResult _BasicOtherMergeDelete(BasicOtherMerge otherMerge)
        {
            BasicOtherMerge otherMerge_db = DataContext.BasicOtherMerges.Find(otherMerge.ID);
            otherMerge.BasicInfoID = otherMerge_db.BasicInfoID;
            DataContext.BasicOtherMerges.Remove(otherMerge_db);
            DataContext.SaveChanges();
            return _BasicOtherMergeList((Guid)otherMerge.BasicInfoID);
        }
        #endregion 合并其它疾病及用药

        #region 历史记录
        public ActionResult BasicInfoHisGridList(Guid basicInfoID)
        {
            return View(basicInfoID);
        }

        [GridAction]
        public ActionResult _BasicHisGridList(Guid basicInfoID)
        {
            //List<DateTime> t;
            List<KeyValuePair<DateTime, string>> t;
            //           List<KeyValuePair<DateTime, String>>
            List<KeyValuePair<DateTime, string>> times = DataContext.FamilyHistories
                .Where(f => f.BasicInfoID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            List<KeyValuePair<DateTime, string>> temps = DataContext.FamilyHistories
                .Where(f => f.MasterID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            temps = DataContext.AllergyHistories
                .Where(f => f.BasicInfoID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            temps = DataContext.AllergyHistories
                .Where(f => f.MasterID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            temps = DataContext.BasicInfoes
                .Where(f => f.ID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            temps = DataContext.BasicInfoes
                .Where(f => f.MasterID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            temps = DataContext.BasicChemoes
                .Where(f => f.BasicInfoID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            temps = DataContext.BasicChemoes
                .Where(f => f.MasterID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            temps = DataContext.BasicOtherCures
                .Where(f => f.BasicInfoID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t.ToList();
            temps = DataContext.BasicOtherCures
                .Where(f => f.MasterID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t.ToList();
            temps = DataContext.BasicOtherMerges
                .Where(f => f.BasicInfoID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            temps = DataContext.BasicOtherMerges
                .Where(f => f.MasterID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            temps = DataContext.BasicRadioes
                .Where(f => f.BasicInfoID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            temps = DataContext.BasicRadioes
                .Where(f => f.MasterID == basicInfoID)
                //.SelectMany(f => f.Archives)
                .AsEnumerable()
                .Distinct()
                .Select(a => new KeyValuePair<DateTime, string>(a.LastModifyTime, a.LastModifier.RealName))
                .ToList();
            t = times.Union(temps).ToList();
            times = t;
            /*List<BasicInfo> basicInfoes = DataContext.BasicInfoes
                .Include(l => l.Creater)
                .Include(l => l.LastModifier).ToList().Where(l => l.MasterID == basicInfoID).Select(basicInfo =>
                new BasicInfo
                {
                    ID = basicInfo.ID,
                    CRF = basicInfo.CRF,
                    CRFID = basicInfo.CRFID,
                    LastModifyTime = basicInfo.LastModifyTime,
                    LastModifier = new Member { RealName = basicInfo.LastModifier.RealName },
                    CreateTime = basicInfo.CreateTime,
                    Creater = new Member { RealName = basicInfo.Creater.RealName },
                    MasterID = basicInfo.MasterID,
                }).ToList();
            return View(new GridModel(basicInfoes));*/

            t = times.OrderByDescending(f => f.Key.Date).ThenByDescending(f => f.Key.TimeOfDay).ToList();
            times = t;
            List<BasicInfo> basicInfoes = new List<BasicInfo>();
            BasicInfo basicInfo, binfo;
            BasicInfo record = DataContext.BasicInfoes.Find<BasicInfo>(basicInfoID);
            bool flag = true;
            foreach (KeyValuePair<DateTime, String> kp in times)
            {
                if (flag)
                {
                    flag = false;
                    continue;
                }
                //for (int i = 1; i < times.Count; i++)
                //{
                List<BasicInfo> b1 = DataContext.BasicInfoes
                    .Where(f => f.ID == basicInfoID)
                    //.SelectMany(f => f.Archives)
                    .AsEnumerable()
                    .Distinct()
                    .ToList();
                List<BasicInfo> b2 = DataContext.BasicInfoes
                    .Where(f => f.MasterID == basicInfoID)
                    //.SelectMany(f => f.Archives)
                    .AsEnumerable()
                    .Distinct()
                    .ToList();
                List<BasicInfo> b3 = b1.Union(b2).OrderByDescending(f => f.LastModifyTime).ToList();
                binfo = (from h in b3
                         where h.LastModifyTime <= kp.Key
                         orderby h.LastModifyTime descending
                         select h).First();
                basicInfo = new BasicInfo();
                basicInfo.ID = record.ID;
                basicInfo.CreateTime = binfo.CreateTime;
                basicInfo.Creater = new Member { RealName = binfo.Creater.RealName };
                basicInfo.LastModifyTime = kp.Key;
                basicInfo.LastModifier = new Member { RealName = kp.Value };
                /*basicInfo.AdmissionCode = binfo.AdmissionCode;
                basicInfo.AgreeTime = binfo.AgreeTime;
                basicInfo.Archives = null;
                basicInfo.BottomCutEdge = binfo.BottomCutEdge;
                basicInfo.Breath = binfo.Breath;
                basicInfo.CaseCode = binfo.CaseCode;
                basicInfo.Course = binfo.Course;
                basicInfo.CreaterID = null;
                basicInfo.CRF = binfo.CRF;
                basicInfo.CRFID = binfo.CRFID;
                basicInfo.Distance = binfo.Distance;
                basicInfo.Dukes = binfo.Dukes;
                basicInfo.ECOG = binfo.ECOG;
                basicInfo.HeartRate = binfo.HeartRate;
                basicInfo.Height = binfo.Height;
                basicInfo.ID = binfo.ID;
                basicInfo.InfiltrationPlace = binfo.InfiltrationPlace;
                basicInfo.IsDeleted = false;
                basicInfo.KPS = binfo.KPS;
                basicInfo.LymphMove = binfo.LymphMove;
                basicInfo.Master = null;
                basicInfo.MasterID = null;
                basicInfo.MaxBP = binfo.MaxBP;
                basicInfo.MedicineCode = binfo.MedicineCode;
                basicInfo.MinBP = binfo.MinBP;
                basicInfo.Office = binfo.Office;
                basicInfo.OperationHospital = binfo.OperationHospital;
                basicInfo.OperationTime = binfo.OperationTime;
                basicInfo.Pathology = binfo.Pathology;
                basicInfo.PathologyCode = binfo.PathologyCode;
                basicInfo.PathologyType = binfo.PathologyType;
                basicInfo.PulseEmbolus = binfo.PulseEmbolus;
                basicInfo.Source = binfo.Source;
                basicInfo.Split = binfo.Split;
                basicInfo.Temperature = binfo.Temperature;
                basicInfo.TNM = binfo.TNM;
                basicInfo.TopCutEdge = binfo.TopCutEdge;
                basicInfo.TumorHeight = binfo.TumorHeight;
                basicInfo.TumorLength = binfo.TumorLength;
                basicInfo.TumorPlace = binfo.TumorPlace;
                basicInfo.TumorRemark = binfo.TumorRemark;
                basicInfo.TumorWidth = binfo.TumorWidth;
                basicInfo.Weight = binfo.Weight;
                basicInfo.WestDiagnose = binfo.WestDiagnose;*/

                /*IEnumerable<BasicChemo> bc = (from f in record.Chemos
                                              where f.LastModifyTime <= times[i]
                                              orderby f.LastModifyTime descending
                                              group f by f.BasicInfoID into g
                                              select g.First());
                basicInfo.Chemos = bc.ToList();*/
                basicInfoes.Add(basicInfo);
            }
            return View(new GridModel(basicInfoes));
        }

        //public ActionResult _BasicInfoDetail(Guid basicInfoID, DateTime lastModifyTime)
        public ActionResult _BasicInfoDetail(Guid basicInfoID, string tt)
        //public ActionResult _BasicInfoDetail(Guid basicInfoID)
        {
            //Guid basicInfoID = Guid.NewGuid();
            //DateTime lastModifyTime = DateTime.Now;
            DateTime lastModifyTime = Convert.ToDateTime(tt);
            BasicInfo basicInfo;
            BasicInfo record = DataContext.BasicInfoes
                .Include(b => b.CRF)
                .Include(b => b.CRF.Patient)
                .Find<BasicInfo>(basicInfoID);
            List<BasicInfo> b1 = DataContext.BasicInfoes
                    .Where(f => f.ID == basicInfoID)
                    .AsEnumerable()
                    .Distinct()
                    .ToList();
            List<BasicInfo> b2 = DataContext.BasicInfoes
                .Where(f => f.MasterID == basicInfoID)
                .AsEnumerable()
                .Distinct()
                .ToList();
            List<BasicInfo> b3 = b1.Union(b2).OrderByDescending(f => f.LastModifyTime).ToList();
            basicInfo = (from h in b3
                         where h.LastModifyTime <= lastModifyTime
                         orderby h.LastModifyTime descending
                         select h).First();
            basicInfo.LastModifyTime = lastModifyTime;
            basicInfo.CRF = record.CRF;
            basicInfo.CRFID = record.CRFID;
            basicInfo.CRF.Patient.Gender = record.CRF.Patient.Gender;
            basicInfo.CRF.Patient.Birthday = record.CRF.Patient.Birthday;
            basicInfo.Archives = null;
            basicInfo.IsDeleted = false;
            /*basicInfo = new BasicInfo();
            basicInfo.CreateTime = binfo.CreateTime;
            basicInfo.Creater = new Member { RealName = binfo.Creater.RealName };
            basicInfo.LastModifyTime = lastModifyTime;
            basicInfo.LastModifier = new Member { RealName = binfo.LastModifier.RealName };
            basicInfo.AdmissionCode = binfo.AdmissionCode;
            basicInfo.AgreeTime = binfo.AgreeTime;
            basicInfo.Archives = null;
            basicInfo.BottomCutEdge = binfo.BottomCutEdge;
            basicInfo.Breath = binfo.Breath;
            basicInfo.CaseCode = binfo.CaseCode;
            basicInfo.Course = binfo.Course;
            basicInfo.CreaterID = null;
            basicInfo.CRF = binfo.CRF;
            basicInfo.CRFID = binfo.CRFID;
            basicInfo.Distance = binfo.Distance;
            basicInfo.Dukes = binfo.Dukes;
            basicInfo.ECOG = binfo.ECOG;
            basicInfo.HeartRate = binfo.HeartRate;
            basicInfo.Height = binfo.Height;
            basicInfo.ID = binfo.ID;
            basicInfo.InfiltrationPlace = binfo.InfiltrationPlace;
            basicInfo.IsDeleted = false;
            basicInfo.KPS = binfo.KPS;
            basicInfo.LymphMove = binfo.LymphMove;
            basicInfo.Master = null;
            basicInfo.MasterID = null;
            basicInfo.MaxBP = binfo.MaxBP;
            basicInfo.MedicineCode = binfo.MedicineCode;
            basicInfo.MinBP = binfo.MinBP;
            basicInfo.Office = binfo.Office;
            basicInfo.OperationHospital = binfo.OperationHospital;
            basicInfo.OperationTime = binfo.OperationTime;
            basicInfo.Pathology = binfo.Pathology;
            basicInfo.PathologyCode = binfo.PathologyCode;
            basicInfo.PathologyType = binfo.PathologyType;
            basicInfo.PulseEmbolus = binfo.PulseEmbolus;
            basicInfo.Source = binfo.Source;
            basicInfo.Split = binfo.Split;
            basicInfo.Temperature = binfo.Temperature;
            basicInfo.TNM = binfo.TNM;
            basicInfo.TopCutEdge = binfo.TopCutEdge;
            basicInfo.TumorHeight = binfo.TumorHeight;
            basicInfo.TumorLength = binfo.TumorLength;
            basicInfo.TumorPlace = binfo.TumorPlace;
            basicInfo.TumorRemark = binfo.TumorRemark;
            basicInfo.TumorWidth = binfo.TumorWidth;
            basicInfo.Weight = binfo.Weight;
            basicInfo.WestDiagnose = binfo.WestDiagnose;*/

            IEnumerable<BasicChemo> bc = (from f in record.Chemos
                                          where f.LastModifyTime <= lastModifyTime
                                          orderby f.LastModifyTime descending
                                          group f by f.BasicInfoID into g
                                          select g.First());
            basicInfo.Chemos = bc.ToList();
            IEnumerable<BasicRadio> br = (from f in record.Radios
                                          where f.LastModifyTime <= lastModifyTime
                                          orderby f.LastModifyTime descending
                                          group f by f.BasicInfoID into g
                                          select g.First());
            basicInfo.Radios = br.ToList();
            IEnumerable<BasicOtherCure> boc = (from f in record.OtherCures
                                               where f.LastModifyTime <= lastModifyTime
                                               orderby f.LastModifyTime descending
                                               group f by f.BasicInfoID into g
                                               select g.First());
            basicInfo.OtherCures = boc.ToList();
            IEnumerable<BasicOtherMerge> bom = (from f in record.OtherMerges
                                                where f.LastModifyTime <= lastModifyTime
                                                orderby f.LastModifyTime descending
                                                group f by f.BasicInfoID into g
                                                select g.First());
            basicInfo.OtherMerges = bom.ToList();

            return View(basicInfo);
        }
        #endregion
    }
}
